package com.android.manghe.mine.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.Glide.GlideHelper
import com.android.base.tools.MediaUtil
import com.android.base.tools.ToastUtil
import com.android.base.tools.permission.OnPermissionResultListener
import com.android.base.tools.permission.PermissionUtil
import com.android.manghe.R
import com.android.manghe.box.model.MessageEvent
import com.android.manghe.config.Config
import com.android.manghe.config.events.RefreshOrdersEvent
import com.android.manghe.mine.presenter.PMarketShowOrder
import com.android.manghe.view.crop.ImageCropHelper
import com.android.manghe.view.multiselectorview.MultiImageSelectorView
import com.eightbitlab.rxbus.Bus
import com.isseiaoki.simplecropview.CropImageView
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_show_order.*
import kotlinx.android.synthetic.main.activity_show_order.multiImageSelectorView
import me.nereo.multi_image_selector.MultiImageSelector
import me.nereo.multi_image_selector.MultiImageSelectorActivity
import org.greenrobot.eventbus.EventBus

/**
 * 晒单
 * @author ZhangWeiJun
 * @date 2019/5/5
 */

class MarketShowOrderActivity : MVPActivity<PMarketShowOrder>(), OnPermissionResultListener,
    MultiImageSelectorView.OnItemClickListener {
    private val CODE_IMAGE_SELECT = 100
    private val CODE_IMAGE_CROP = 101

    companion object {
        fun showActivity(
            context: Context,
            orderId: String,
            goodId: String,
            picUrl: String,
            title: String
        ) {
            val intent = Intent(context, MarketShowOrderActivity::class.java)
            intent.putExtra("orderId", orderId)
            intent.putExtra("goodId", goodId)
            intent.putExtra("picUrl", picUrl)
            intent.putExtra("title", title)
            context.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_show_order
    }

    override fun initData(savedInstanceState: Bundle?) {
        titleBar.setToolbar("晒单").setTitleAndStatusBgColor(R.color.white)
            .setLeftIcon(R.mipmap.icon_back_black)
        p.setOrderId(intent.getStringExtra("orderId"))
        p.setGoodId(intent.getStringExtra("goodId"))
        p.setOrder_sn(intent.getStringExtra("orderSn"));

        GlideHelper.loadWithHolderErr(this, intent.getStringExtra("picUrl"), ivPic)
        tvName.text = intent.getStringExtra("title")

        multiImageSelectorView.setShowAddImageOnMaximum(false)
        multiImageSelectorView.setOnItemClickListener(this)

        layoutPicTip.setOnClickListener {
            //添加第一个图片
            PermissionUtil.requestPermissions(
                this, this,
                Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA
            )
        }

        btnSubmit.setOnClickListener {
            val rating = ratingBar.progress
            if (rating == 0) {
                ToastUtil.showShort(this, "星级评分不能为空")
                return@setOnClickListener
            }
            val content = etContent.text.toString().trim()
            if (content.isEmpty()) {
                ToastUtil.showShort(this, "评价内容不能为空")
                return@setOnClickListener
            }
            showLoadingDialog()
            p.submit(content, rating)
        }

    }

    override fun onGranted(permissions: MutableList<String>?) {
        MultiImageSelector.create()
            .showCamera(true) // show camera or not. true by default
            .count(3) // max select image size, 9 by default. used width #.multi()
            .single() // multi mode, default mode;
            .origin(p.picList) // original select data set, used width #.multi()
            .start(this, CODE_IMAGE_SELECT)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CODE_IMAGE_SELECT) {
                val arrayList =
                    data?.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT)
                if (arrayList != null && !arrayList.isEmpty()) {
                    ImageCropHelper.startCropFree(
                        this, arrayList.get(0),
                        ImageCropHelper.ImageCropParamsBuilder
                            .create()
                            .compressQuality(90)
                            .cropMode(CropImageView.CropMode.FREE)
                            .outputMaxSize(1280, 1280)
                            .build(), CODE_IMAGE_CROP
                    )
                }

            } else if (requestCode == CODE_IMAGE_CROP) {
                val resultUri = ImageCropHelper.onActivityResult(resultCode, data)
                if (resultUri != null) {
                    val imagePath = MediaUtil.getPath(this, resultUri)
                    p.picList.add(imagePath)
                    layoutPicTip.visibility = View.GONE
                    multiImageSelectorView.visibility = View.VISIBLE
                    multiImageSelectorView.setList(p.picList)
                }
            }
        }
    }


    override fun onDelete(view: View?, position: Int) {
        if (position >= 0 && position < p.picList.size) {
            p.picList.removeAt(position)
            multiImageSelectorView.setList(p.picList)
        }
    }

    override fun onAdd(view: View?) {
        PermissionUtil.requestPermissions(
            this, this,
            Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA
        )
    }

    override fun onItemClick(view: View?, position: Int) {
    }

    override fun onReachTheMaximum() {
    }

    fun submitOk(text: String?) {
        EventBus.getDefault().post(MessageEvent(Config.EVENT_BUS_GET_ALL_ORDER))
        ToastUtil.showShort(this, text)
        finish()
    }

    fun submitFail(text: String?) {
        ToastUtil.showShort(this, if (TextUtils.isEmpty(text)) "晒单成功" else text)
    }

}